using System.Text;

namespace blue.communication{
    using EventArgs = uPLibrary.Networking.M2Mqtt.Messages.MqttMsgPublishEventArgs;
    using EventHandler = uPLibrary.Networking.M2Mqtt.MqttClient.MqttMsgPublishEventHandler;

    public class BtcsClient{
        public delegate void MsgHandler(byte[] msg);
        private MsgHandler msg_handler_;
        private string pub_topic_;
        private string sub_topic_;
        private string broker_ip_;
        private string pub_id_;
        private string sub_id_;
        private MqttPublisher pub_;
        private MqttSubscriber sub_;
 
        public BtcsClient(MsgHandler handler=null){
            pub_topic_ = "btcs/sub";
            sub_topic_ = "btcs/pub";
            broker_ip_ = "127.0.0.1";
            pub_id_ = "btcs-publisher";
            sub_id_ = "btcs-subscriber";
            msg_handler_ = handler==null?defaultMsgHandler:handler;
            // Connect to server
            pub_ = new MqttPublisher(pub_topic_, broker_ip_, pub_id_);
            sub_ = new MqttSubscriber(new string[]{sub_topic_}, broker_ip_
                , sub_id_, btcsHandler);

        }

        public BtcsClient(MsgHandler handler, string pub_topic, string sub_topic
            , string broker_ip, string pub_id, string sub_id)
        {
            pub_topic_ = pub_topic;
            sub_topic_ = sub_topic;
            broker_ip_ = broker_ip;
            pub_id_ = pub_id;
            sub_id_ = sub_id;
            msg_handler_ = handler==null?defaultMsgHandler:handler;
            // Connect to server
            pub_ = new MqttPublisher(pub_topic_, broker_ip_, pub_id_);
            sub_ = new MqttSubscriber(new string[]{sub_topic_}, broker_ip_
                , sub_id_, btcsHandler);
        }

        public bool publish(string msg){
            return pub_.publish(msg);
        }

        public bool publish(byte[] data){
            return pub_.publish(data);
        }

        private void btcsHandler(object sender, EventArgs e){
            msg_handler_(e.Message);
        }

        private void defaultMsgHandler(byte[] data){
            string msg = System.Text.Encoding.UTF8.GetString(data);
            System.Console.WriteLine("Recv(Abandoned) BtcsClient > {0}",msg);
        }
    }
}